 
  

 






<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> 
<html>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=3 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
<head>
 <title>
  Java Practices -> Copy an array 
 </title>
 <link rel="stylesheet" type="text/css" href="../stylesheet8.css" media="all">
 
 <link rel="shortcut icon" href='../images/favicon.ico' type="image/vnd.microsoft.icon">
 <meta name="description" content="Concise presentations of java programming practices, tasks, and conventions, amply illustrated with syntax highlighted code examples.">
 
 <meta name='keywords' content='arraycopy,clone,performance,array,copy,java,java programming,java practices,java idiom,java style,java design patterns,java coding conventions,'>
 
 
</head>
 
<body>


<div class='menu-bar'>
 
  <a href='../home/HomeAction.html' title='Table of Contents'>Home</a> |
  <a href='../vote/VoteSummaryAction-2.html' title='View Poll Results'>Poll</a> |
   
  <A href='../feedback/FeedbackAction451f-2.html?Operation=Show' title='Send Your Feedback'>Wiki</a> |
  <b><a href='../source/SourceAction-2.html' title='Grab Source Code'>Source Code</a></b><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |

  <a href='http://www.web4j.com/Java_Web_Application_Framework_Overview.jsp?From=1' title='Free Download - Java Web Application Framework'><b>WEB4J</b></a> |
  
  <a href='http://www.date4j.net/' title='Replacement for java.util.Date'><b>DATE4J</b></a> |

   <a href='../references/ReferencesAction-2.html' title='References'>Links</a>
   
  <form action='http://www.javapractices.com/search/SearchAction.do' method='get' class='search-form'>
   <input type='text' name='SearchTerms' value="" size=12 maxlength=50 class='search'>
   <input type='submit' value="Search">
  </form>
 
</div>

<P>



  

 






<p class="display-messages">

 

 

</p>


<div class="main-layout">
 
   

 




<div class='page-title'>Copy an array </div>

<div class='main-body'>
 
<br>There are several ways to copy an array :
<ul>

<li>use the various <tt>copyOf</tt> and <tt>copyOfRange</tt> methods of the 
<tt><a href="http://java.sun.com/javase/6/docs/api/java/util/Arrays.html">Arrays</a></tt> class</li> - probably the simplest method

<li>
use <tt>System.<a href="http://java.sun.com/javase/6/docs/api/java/lang/System.html#arraycopy(java.lang.Object, int, java.lang.Object, int, int)">arraycopy</a></tt>
- useful when copying parts of an array</li>


<li>
call its <tt>clone</tt> method, and do a cast - the simplest style, but
only a shallow clone is performed</li>


<li>
use a <tt>for</tt> loop - more than one line, and needs a loop index</li>
</ul>
Example
<p>This example class demonstrates
<ul>
<li>
relative performance of the various methods</li>

<li>
how <tt>clone</tt> is a shallow copy, and leads to independent storage
only for primitive, one dimensional arrays.</li>
</ul>
<br>
<PRE>

<span class='keyword'>import</span> java.util.*;

<span class='keyword'>public</span> <span class='keyword'>final</span> <span class='keyword'>class</span> ArrayCopier {

  <span class='keyword'>public</span> <span class='keyword'>static</span> <span class='keyword'>void</span> main (String... aArguments) {
    String action = aArguments[<span class='literal'>0</span>];
    <span class='keyword'>int</span> numIterations = <span class='literal'>0</span>;
    <span class='keyword'>if</span> ( aArguments.length == <span class='literal'>2</span> ) {
      numIterations = Integer.parseInt( aArguments[<span class='literal'>1</span>] );
    }

    <span class='keyword'>if</span> ( action.equals(<span class='literal'>"performance"</span>) ) {
      demoPerformance( numIterations );
    }
    <span class='keyword'>else</span> <span class='keyword'>if</span> ( action.equals(<span class='literal'>"storage"</span>) ) {
      demoIndependanceOfStorage();
    }
  }

  <span class='comment'>/**
  * Display the time it takes to copy an array in various ways.
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> demoPerformance( <span class='keyword'>int</span> aNumIterations ){
    Stopwatch stopwatch = <span class='keyword'>new</span> Stopwatch();
    <span class='keyword'>int</span>[] numbers = {<span class='literal'>1</span>,<span class='literal'>2</span>,<span class='literal'>3</span>,<span class='literal'>4</span>,<span class='literal'>5</span>,<span class='literal'>6</span>,<span class='literal'>7</span>,<span class='literal'>8</span>,<span class='literal'>9</span>,<span class='literal'>10</span>};

    stopwatch.start();
    copyUsingClone( numbers, aNumIterations );
    stopwatch.stop();
    System.out.println(<span class='literal'>"Using clone: "</span> + stopwatch);

    stopwatch.start();
    copyUsingArraycopy( numbers, aNumIterations );
    stopwatch.stop();
    System.out.println(<span class='literal'>"Using System.arraycopy: "</span> + stopwatch);

    stopwatch.start();
    copyUsingArraysCopyOf( numbers, aNumIterations );
    stopwatch.stop();
    System.out.println(<span class='literal'>"Using Arrays.copyOf: "</span> + stopwatch);

    stopwatch.start();
    copyUsingForLoop( numbers, aNumIterations );
    stopwatch.stop();
    System.out.println(<span class='literal'>"Using for loop: "</span> + stopwatch);
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> copyUsingClone( <span class='keyword'>int</span>[] aArray , <span class='keyword'>int</span> aNumIterations) {
    <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span> ; idx &lt; aNumIterations; ++idx ) {

      <span class='keyword'>int</span>[] copy = (<span class='keyword'>int</span>[])aArray.clone();

    }
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> copyUsingArraycopy( <span class='keyword'>int</span>[] aArray , <span class='keyword'>int</span> aNumIterations) {
    <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span> ; idx &lt; aNumIterations; ++idx ) {

      <span class='keyword'>int</span> [] copy = <span class='keyword'>new</span> <span class='keyword'>int</span>[aArray.length];
      System.arraycopy( aArray, <span class='literal'>0</span>, copy, <span class='literal'>0</span>, aArray.length );

    }
  }

  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> copyUsingArraysCopyOf( <span class='keyword'>int</span>[] aArray , <span class='keyword'>int</span> aNumIterations) {
    <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span> ; idx &lt; aNumIterations; ++idx ) {

      <span class='keyword'>int</span>[] copy = Arrays.copyOf(aArray, aArray.length);

    }
  }


  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> copyUsingForLoop( <span class='keyword'>int</span>[] aArray , <span class='keyword'>int</span> aNumIterations) {
    <span class='keyword'>for</span> ( <span class='keyword'>int</span> iterIdx = <span class='literal'>0</span> ; iterIdx &lt; aNumIterations; ++iterIdx ) {

      <span class='keyword'>int</span> [] copy = <span class='keyword'>new</span> <span class='keyword'>int</span>[aArray.length];
      <span class='keyword'>for</span> ( <span class='keyword'>int</span> idx = <span class='literal'>0</span>; idx &lt; aArray.length; ++idx ) {
        copy[idx] = aArray[idx];
      }

    }
  }

  <span class='comment'>/**
  * (The for-loop and System.arraycopy styles clearly have independent
  * storage, and are not exercised in this method.)
  */</span>
  <span class='keyword'>private</span> <span class='keyword'>static</span> <span class='keyword'>void</span> demoIndependanceOfStorage() {
    <span class='comment'>//a clone of a one-dimensional array has independent storage
</span>    <span class='keyword'>int</span>[] numbers = {<span class='literal'>1</span>,<span class='literal'>1</span>,<span class='literal'>1</span>,<span class='literal'>1</span>};
    <span class='keyword'>int</span>[] numbersClone = (<span class='keyword'>int</span>[])numbers.clone();
    <span class='comment'>//set 0th element to 0, and compare
</span>    numbersClone[<span class='literal'>0</span>] = <span class='literal'>0</span>;
    System.out.println(<span class='literal'>"Altered clone has NOT affected original:"</span>);
    System.out.println(<span class='literal'>"numbersClone[0]: "</span> + numbersClone[<span class='literal'>0</span>] );
    System.out.println(<span class='literal'>"numbers[0]: "</span> +  numbers[<span class='literal'>0</span>] );

    <span class='comment'>//the clone of a multi-dimensional array does *not* have
</span>    <span class='comment'>//independant storage
</span>     <span class='keyword'>int</span>[][] matrix = { {<span class='literal'>1</span>,<span class='literal'>1</span>}, {<span class='literal'>1</span>,<span class='literal'>1</span>} };
     <span class='keyword'>int</span>[][] matrixClone = (<span class='keyword'>int</span>[][])matrix.clone();
     <span class='comment'>//set 0-0th element to 0, and compare
</span>     matrixClone[<span class='literal'>0</span>][<span class='literal'>0</span>] = <span class='literal'>0</span>;
     System.out.println(<span class='literal'>"Altered clone has affected original:"</span>);
     System.out.println(<span class='literal'>"matrixClone element 0-0:"</span> + matrixClone[<span class='literal'>0</span>][<span class='literal'>0</span>]);
     System.out.println(<span class='literal'>"matrix element 0-0: "</span> + matrix[<span class='literal'>0</span>][<span class='literal'>0</span>]);

     <span class='comment'>//the clone of an array of objects as well is only shallow
</span>     Date[] dates = { <span class='keyword'>new</span> Date() };
     System.out.println(<span class='literal'>"Original date: "</span> + dates[<span class='literal'>0</span>]);
     Date[] datesClone = (Date[])dates.clone();
     datesClone[<span class='literal'>0</span>].setTime(<span class='literal'>0</span>);
     System.out.println(<span class='literal'>"Altered clone has affected original:"</span>);
     System.out.println(<span class='literal'>"datesClone[0]:"</span> + datesClone[<span class='literal'>0</span>]);
     System.out.println(<span class='literal'>"dates[0]: "</span> + dates[<span class='literal'>0</span>]);
  }
} 
</PRE>
<br>
<br><tt>System.arraycopy</tt> seems to have slightly better performance.
Differences between the various styles are small, however, and
would often be regarded as a micro-optimization :
<p><tt>>java -cp . -Xint ArrayCopier performance 250000</tt>
<tt>
<br>Using clone: 93 ms
<br>Using System.arraycopy: 110 ms
<br>Using Arrays.copyOf: 187 ms
<br>Using for loop: 422 ms
</tt>
<p>The above example use the 
<tt><a href="http://java.sun.com/javase/6/docs/technotes/tools/windows/java.html#nonstandard" title="Non-standard options for java interpreter">-Xint</a></tt> 
option to turn off the Just
In Time compiler. Here, bytecodes are interpreted at runtime, but never
compiled by the HotSpot compiler into native code. This provides a uniform
environment for executing tests of relative execution time, since there
is no "warm-up" period.
<p>Example run demonstrating independence of storage, or lack thereof :
<p><tt>>java -cp . ArrayCopier storage</tt>
<br><tt>Altered clone has NOT affected original:</tt>
<br><tt>numbersClone[0]: 0</tt>
<br><tt>numbers[0]: 1</tt>
<br><tt>Altered clone has affected original:</tt>
<br><tt>matrixClone element 0-0:0</tt>
<br><tt>matrix element 0-0: 0</tt>
<br><tt>Original date: Mon Sep 30 15:47:58 EDT 2002</tt>
<br><tt>Altered clone has affected original:</tt>
<br><tt>datesClone[0]:Wed Dec 31 19:00:00 EST 1969</tt>
<br><tt>dates[0]: Wed Dec 31 19:00:00 EST 1969</tt>
<br>
<br>

</div>




<div class='topic-section'>See Also :</div>
<div class='main-body'>
 
  
  <a href='TopicActiondd78-2.html?Id=85'>Time execution speed</a> <br>
 
</div>


<div class='topic-section'>Would you use this technique?</div>
<div class='main-body'>
  
  <form action="http://www.javapractices.com/vote/AddVoteAction.do" method='post'>
    Yes<input type='radio' name='Choice' value='Y' >
    &nbsp;&nbsp;No<input type='radio' name='Choice' value='N'>
    &nbsp;&nbsp;Undecided<input type='radio' name='Choice' value="?" >
    &nbsp;&nbsp;<input type=submit value="Vote" >
    <input type='hidden' name='Operation' value='Apply'>
    <input type='hidden' name='TopicId' value='3'>
  </form>
</div>

<div style='height:10.0em;'></div>

 
 
</div>

  

 





<div align='center' class='legalese'>  
&copy; 2011 Hirondelle Systems |
<a href='../source/SourceAction-2.html'><b>Source Code</b></a><IMG class='no-margin' SRC="../images/goldstar.gif" ALT=""> |
<a href="mailto:webmaster@javapractices.com">Contact</a> |
<a href="http://creativecommons.org/licenses/by-nc-sa/1.0/">License</a> |
<a href='../apps/cjp.rss'>RSS</a>
<!-- ukey="2AC36CD2" -->
<!-- ckey="16DF3D87" -->
<br>

 Individual code snippets can be used under this <a href='../LICENSE.txt'>BSD license</a> - Last updated on June 6, 2010.<br>
 Over 150,000 unique IPs last month - <span title='Java Practices 2.6.5, Mon May 16 00:00:00 EDT 2011'>Built with</span> <a href='http://www.web4j.com/'>WEB4J</a>.<br>
 - In Memoriam : Bill Dirani -
</div>

<script src="../../www.google-analytics.com/urchin.js" type="text/javascript">
</script>
<script type="text/javascript">
_uacct = "UA-2633428-1";
urchinTracker();
</script>



</body>

<!-- Mirrored from www.javapractices.com/topic/TopicAction.do;jsessionid=4FCCB481C702D708A7360133D128E359?Id=3 by HTTrack Website Copier/3.x [XR&CO'2010], Sun, 12 Jun 2011 17:27:36 GMT -->
<!-- Added by HTTrack --><meta http-equiv="content-type" content="text/html;charset=UTF-8"><!-- /Added by HTTrack -->
</html>
